package com.py.credit.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Column;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.service.ColumnService;
import com.py.credit.service.ContentService;
import com.py.credit.service.RemoteBaseService;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/column")
public class ColumnController {

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private ColumnService columnService;

	@Autowired
	private ContentService contentService;

	/**
	 * @api {get} /column/operateSharingColumn.json 维护常用数据项
	 * @apiName operateSharingColumn
	 * @apiVersion 0.0.1
	 * @apiGroup 常用数据项
	 * @apiParam {String} addColumn 表所属数据库节点id (可选)
	 * @apiParam {String} delColumn 搜索条件 (可选)
	 * @apiParam {String} updateColumn 每页展示条数 (可选)
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */

	@RequestMapping(value = "/operateSharingColumn.json")
	public RestServiceResult<String> addSharingColumn(
			@RequestParam(value = "addColumn", defaultValue = "", required = true) String addColumn,
			@RequestParam(value = "delColumn", defaultValue = "", required = true) String delColumn,
			@RequestParam(value = "updateColumn", defaultValue = "", required = true) String updateColumn) {

		List<Column> addColumns = JSONArray.parseArray(addColumn, Column.class);
		List<Column> updateColumns = JSONArray.parseArray(updateColumn, Column.class);
		List<Column> delColumns = JSONArray.parseArray(delColumn, Column.class);
		columnService.updateColumn(addColumns, updateColumns, delColumns);
		return new RestServiceResult<String>();

	}

	@RequestMapping(value = "/getSharingColumnList.json")
	public RestServiceResult<List<Column>> getSharingColumnList(
			@RequestParam(value = "metricCode", defaultValue = "", required = true) String metricCode,
			@RequestParam(value = "metricName", defaultValue = "", required = true) String metricName) {

		List<Column> tableList = columnService.getList(metricCode, metricName);

		return new RestServiceResult<List<Column>>(tableList);

	}

	/**
	 * @api {get} /column/getAllTimeMetricByTableId.json 获取表中所有时间类型字段
	 * @apiName getAllTimeMetricByTableId
	 * @apiVersion 0.0.1
	 * @apiGroup 常用数据项
	 * @apiParam {Long} tableId
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@RequestMapping(value = "/getAllTimeMetricByTableId.json")
	public RestServiceResult<List<Map<String, String>>> getAllTimeMetricByTableId(
			@RequestParam(value = "tableId", defaultValue = "", required = true) Long tableId) {
		RestServiceResult<List<Map<String, String>>> result = new RestServiceResult<List<Map<String, String>>>();
		List<Map<String, String>> tableList = null;
		try {
			tableList = columnService.getAllTimeMetricByTableId(tableId);
			result.setData(tableList);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error("ColumnController#getAllTimeMetricByTableId",
					"获取表中所有时间类型字段异常！ERROR：" + e.getMessage(), e);
			return result;
		}
	}

	/**
	 * @api {get} /column/getTableColumns.json 获取数据表字段信息
	 * @apiName getTableColumns
	 * @apiVersion 0.0.1
	 * @apiGroup 常用数据项
	 * @apiParam {Integer} tableId 数据资源表ID
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@ResponseBody
	@RequestMapping(value = "/getTableColumns.json")
	public RestServiceResult<List<Column>> getTableColumns(
			@RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId,
			@RequestParam(value = "contentId", defaultValue = "", required = true) Integer contentId,
			HttpServletRequest request) {
		RestServiceResult<List<Column>> result = new RestServiceResult<>();
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getTemplate", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long topDeptId = userInfo.getOfficeId();
		String pIds = userInfo.getAllParentId();
		if (StringUtils.isNotBlank(pIds)) {
			String t = StringUtils.split(pIds, ",")[0];
			topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
		}
		try {
			String tipId = tableId + "_" + topDeptId;
			TableResult table = contentService.getTableColumns(tableId, contentId, tipId);
			List<Column> data = table.getColumns();
			// List<Column> data = columnService.getListByTableId(tableId);
			result.setData(data);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取数据表字段信息异常！");
			ExceptionLogger.error("ColumnController#getTableColumns", "获取数据表字段信息异常！ERROR：" + e.getMessage(), e);
			return result;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getTableColumns1.json")
	public RestServiceResult<List<Column>> getTableColumns1(
			@RequestParam(value = "tableId", defaultValue = "") Integer tableId, Page page) {
		RestServiceResult<List<Column>> result = new RestServiceResult<>();
		try {
			List<Column> data = columnService.getListByTableId1(tableId, page);
			result.setData(data);
			result.setCount(page.getTotalCount());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取数据表字段信息异常！");
			ExceptionLogger.error("ColumnController#getTableColumns", "获取数据表字段信息异常！ERROR：" + e.getMessage(), e);
			return result;
		}
	}
}
